package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import donain.User;
import exception.LoginException;

import service.UserService;
import utilts.GetRequestJsonUtils;
import utilts.Response;
import utilts.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LogServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("login");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        JSONObject jsObject=null;
        HttpServletRequest httpServletRequest=(HttpServletRequest)req;
        try {
            jsObject= GetRequestJsonUtils.getRequestJsonObject(req);
        }catch (Exception e){
            e.printStackTrace();
            Response build=Response.build(ResponseCode.ERROR,e.getMessage());
            resp.getWriter().write(JSON.toJSON(build).toString());
            resp.setContentType("application/json;charset=utf-8");
        }

        String userString=jsObject.getString("user");
        User user= JSON.parseObject(userString,User.class);
        UserService userService= new UserService();
        User userDB=null;
        Response build=null;
        try {
            userDB=userService.login(user);
            HttpSession session=req.getSession();
            session.setAttribute("user",userDB);
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            resp.addCookie(cookie);
            String ulr=null;
            if(userDB.getRole().equals("超级用户")){
                ulr="/api/login/home";
            }
            else
                ulr="/client";
             build=Response.build(ResponseCode.SUCCESS_LOGIN,ulr);
        } catch (LoginException e) {
            e.printStackTrace();
          build=Response.build(e.getResponseCode());
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
